<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item class="breadcrumb_active_item"
            >成绩查询</el-breadcrumb-item
          >
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <div class="results_list_content">
        <!-- 搜索框 -->
        <el-row>
          <el-col :span="24">
            <div class="results_list_search">
              <div>筛选：</div>
              <el-select
                v-model="levelSearch"
                placeholder="请选择篮球等级"
                size="mini"
                style="width: 150px; margin-left: 5px"
                clearable
                @change="levelSearchFn"
              >
                <el-option
                  v-for="item in levelList"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                >
                </el-option>
              </el-select>
              <el-select
                v-model="statusSearch"
                placeholder="请选择通过状态"
                size="mini"
                style="width: 150px; margin-left: 5px"
                clearable
                @change="statusSearchFn"
              >
                <el-option
                  v-for="item in statusList"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                >
                </el-option>
              </el-select>
              <el-input
                v-model="searchKey"
                placeholder="请输入"
                size="mini"
                style="width: 150px; margin-left: 5px"
              ></el-input>
              <el-button
                type="primary"
                size="mini"
                style="margin-left: 5px"
                @click="searchFn()"
                >搜索</el-button
              >
            </div>
          </el-col>
        </el-row>
        <!-- 按钮 -->
        <el-row>
          <el-col :span="2">
            <el-button
              type="primary"
              size="mini"
              @click="downloadBtn()"
              :loading="downloadBtnLoading"
              style="width: 110px; margin: 10px 0 20px"
              >{{ downloadBtnText }}</el-button
            >
          </el-col>
        </el-row>
        <!-- 数据列表 -->
        <el-row
          type="flex"
          justify="center"
          v-if="resultsListData != undefined && resultsListData.length > 0"
        >
          <el-col :span="24">
            <el-table
              :data="resultsListData"
              border
              style="width: 100%"
              size="mini"
              :cell-style="cellStyleFn"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                width="55"
                align="center"
                :selectable="selecTableFn"
              >
              </el-table-column>

              <el-table-column
                prop="level"
                label="考试项目级别"
                align="center"
                width="200"
                :formatter="formatterLevelFn"
              ></el-table-column>

              <el-table-column
                prop="title"
                label="考试项目"
                align="center"
                min-width="220"
              ></el-table-column>

              <el-table-column
                prop="place"
                label="考点"
                width="200"
                align="center"
              ></el-table-column>

              <el-table-column
                prop="exam_date"
                label="考试时间"
                align="center"
                width="150"
              ></el-table-column>

              <el-table-column
                prop="stu_name"
                label="考生名称"
                width="150"
                align="center"
              ></el-table-column>

              <el-table-column
                prop="stu_identity_number"
                label="身份证号"
                width="220"
                align="center"
              ></el-table-column>

              <el-table-column
                prop="score"
                label="分数"
                width="100"
                align="center"
              ></el-table-column>

              <el-table-column
                prop="pass_status"
                label="通过状态"
                width="150"
                align="center"
                :formatter="formatterStatusFn"
              ></el-table-column>

              <el-table-column
                label="操作"
                width="100"
                itemprop=""
                align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="detailFn(scope.$index, scope.row)"
                    :disabled="scope.row.pass_status == 1"
                    >证书</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row
          type="flex"
          justify="center"
          v-if="resultsListData != undefined && resultsListData.length > 0"
        >
          <el-col :span="24">
            <div class="results_list_pagination">
              <el-pagination
                @size-change="listSizeChange"
                @current-change="listCurrentChange"
                :current-page="currentPage"
                :page-sizes="pageSizes"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
              >
              </el-pagination>
            </div>
          </el-col>
        </el-row>
        <el-row v-else>
          <el-empty description="暂无成绩"></el-empty>
        </el-row>
      </div>
    </el-row>
    <!-- 二维码弹窗 -->
    <el-dialog
      title="证书"
      :visible.sync="certificateDialogVisible"
      :before-close="dialogClose"
      width="500px"
    >
      <div class="results_list_certificate_box">
        <img
          class="results_list_certificate_img"
          :src="baseAPIUrl + certificateImgUrl"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="dialogClose()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<style src="../../assets/css/results/resultsList.css" scoped></style>

<script>
import { saveAs } from "file-saver";
import JSZip from "jszip";

export default {
  name: "ResultsList",
  components: {},
  data() {
    return {
      baseAPIUrl: this.$store.state.baseAPIUrl, //默认路径
      gradeId: "", // 当前选择等级id
      levelSearch: "", // 等级筛选
      statusSearch: "", // 状态筛选
      searchKey: "", // 搜索关键词
      resultsListData: [], // 报名列表数据
      currentPage: 1, // 当前页
      pageSizes: [10, 20, 50, 100], // 可选页容量
      pageSize: 10, // 当前页容量
      total: 0, // 总条数
      statusList: [
        {
          key: 1,
          value: "不合格",
        },
        {
          key: 2,
          value: "合格",
        },
        {
          key: 3,
          value: "良好",
        },
        {
          key: 4,
          value: "优秀",
        },
      ], // 状态列表
      levelList: [], // 等级列表
      certificateDialogVisible: false, // 证书显示
      certificateImgUrl: "", // 证书显示路径
      multipleSelection: [], // 已勾选列表
      loadingKey: false,
      loadingText: "",
      downloadBtnText: "批量下载证书",
      downloadBtnLoading: false,
      downloadMax: 0,
      downloadNow: 0,
    };
  },
  created: function () {
    this.getListDataFn();
    this.levelList = JSON.parse(JSON.stringify(this.$store.state.levelList));
  },
  methods: {
    // 等级筛选
    levelSearchFn: function (val) {
      this.levelSearch = val;
      this.searchFn();
    },
    // 通过状态筛选
    statusSearchFn: function (val) {
      this.statusSearch = val;
      this.searchFn();
    },
    // 搜索按钮
    searchFn: function () {
      this.currentPage = 1;
      this.getListDataFn();
    },
    // 关闭弹窗
    dialogClose: function () {
      this.certificateDialogVisible = false;
    },
    // 查询列表数据
    getListDataFn: function () {
      let that = this;
      let url = "/mobile/myscores";
      let data = {
        keywords: this.searchKey,
        page: this.currentPage,
        perPage: this.pageSize,
        level: this.levelSearch,
        pass_status: this.statusSearch,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.resultsListData = response.list;
            that.total = response.total_count;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 设置单元格字体颜色
    cellStyleFn: function ({ row, columnIndex }) {
      let style = "";
      if (columnIndex == 8) {
        if (row.pass_status == 1) {
          style = "color: #F6705E";
        } else {
          style = "color: #8ECF5F";
        }
      }
      return style;
    },
    // 状态格式化
    formatterStatusFn: function (row) {
      let status = row.pass_status;
      let text = "";
      this.statusList.forEach(function (item) {
        if (item.key == status) {
          text = item.value;
        }
      });
      return text;
    },
    // 页容量改变
    listSizeChange: function (val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.getListDataFn();
    },
    // 当前页改变
    listCurrentChange: function (val) {
      this.currentPage = val;
      this.getListDataFn();
    },
    // 考试等级格式化
    formatterLevelFn: function (row) {
      let level = row.level;
      let text = "";
      this.levelList.forEach(function (item) {
        if (item.key == level) {
          text = item.value;
        }
      });
      return text;
    },
    // 证书
    detailFn: function (index, row) {
      this.certificateImgUrl = row.certificate;
      this.$nextTick(function () {
        this.certificateDialogVisible = true;
      });
    },
    // 勾选改变
    handleSelectionChange: function (val) {
      this.multipleSelection = val;
    },
    // 设置是否能勾选
    selecTableFn: function (row) {
      if (
        row.pass_status != 1 &&
        row.certificate_print != null &&
        row.certificate_print != "" &&
        row.certificate_print != undefined
      ) {
        return true;
      } else {
        return false;
      }
    },
    // 下载
    downloadFileFn: function (url) {
      return new Promise((resolve, reject) => {
        fetch(url)
          .then((res) => res.blob())
          .then((blob) => {
            resolve(blob);
          })
          .catch((error) => {
            reject(error.toString());
          });
      });
    },
    // 下载按钮
    downloadBtn: function () {
      let that = this;
      let upList = [];
      const zip = new JSZip();
      const promises = [];
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(function (item) {
          if (
            item.certificate_print != null &&
            item.certificate_print != "" &&
            item.certificate_print != undefined
          ) {
            let name = item.stu_name + item.exam_stu_number + ".png";
            upList.push(item);
            const promise = that
              .downloadFileFn(that.baseAPIUrl + item.certificate_print)
              .then((data) => {
                let cil = 0;
                that.downloadNow++;
                cil = Math.floor((that.downloadNow / that.downloadMax) * 100);
                that.downloadBtnText = "下载中 " + cil + "%";
                zip.file(name, data);
              });
            promises.push(promise);
          }
        });
        this.downloadBtnLoading = true;
        this.downloadBtnText = "下载中...";
        this.downloadMax = upList.length;
        this.downloadNow = 0;
        Promise.all(promises).then(() => {
          zip
            .generateAsync({
              type: "blob",
            })
            .then((content) => {
              saveAs(content, "证书.zip");
              this.downloadBtnLoading = false;
              this.downloadBtnText = "批量下载证书";
            });
        });
      }
    },
  },
};
</script>
